package com.java.IO.convert_stream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class OutputStreamWriterAPI {
    public static void useOutputStreamWriter(String path, String encode) throws IOException {
        // 创建对象：创建规则主要依赖于构造形参OutputStream的子类。参数2为字符集，默认UTF-8
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(path), encode);
        
        // write：写出数据到目的地，若参数为整数则会转为ASCII对应的字符
        outputStreamWriter.write(97); // a
        outputStreamWriter.write('9'); // 9
        outputStreamWriter.write('中'); // 中
        outputStreamWriter.write('中'); // 中
        outputStreamWriter.write("\r\n"); // 换行(Windows\r\n、Linux\n、Mac\r)
        outputStreamWriter.write(new char[]{'a', '哈', 'c', 'd'}); // a哈cd
        outputStreamWriter.write(new char[]{'a', '哈', 'c', 'd', 101, 102, 103}, 3, 2); // de
        outputStreamWriter.write("啊啊啊Hello"); // 啊啊啊Hello
        outputStreamWriter.write("啊啊啊Hello", 3, 2); // He
        
        // getEncoding：获取当前流字符集
        System.out.println(outputStreamWriter.getEncoding());
        
        // close：关闭流并释放资源
        outputStreamWriter.close();
    }
    
    public static void main(String[] args) throws IOException {
        // 使用IDEA打开不乱码，因为IDEA使用的字符集为UTF-8。不乱码的输出在方法注释内
        useOutputStreamWriter("File和IO流\\com\\java\\files\\convert_stream_utf8.txt", "UTF-8");
        // 使用IDEA打开乱码，因为IDEA使用的字符集为UTF-8
        useOutputStreamWriter("File和IO流\\com\\java\\files\\convert_stream_gbk.txt", "GBK");
    }
}
